package com.toocms.jinjuhang.ui.mine.management_system.withdraw

import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.WithdrawRecordsData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent

class WithdrawRecordModel(application: Application) : BaseViewModel<BaseModel>(application) {
    private var p = 1
    val items = ObservableArrayList<WithdrawRecordItemModel>()
    val itemBinding = ItemBinding.of<WithdrawRecordItemModel>(
        BR.withdrawRecordItemModel,
        R.layout.item_withdraw_record
    )

    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh()
    })

    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        load()
    })


    init {
        refresh(true)
    }

    private fun refresh(isShowLoading: Boolean = false) {
        p = 1
        withdrawRecords(p, isShowLoading)
    }

    private fun load() {
        p++
        withdrawRecords(p)
    }

    private fun withdrawRecords(p: Int, isShowLoading: Boolean = false) {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["p"] = p.toString()
        requestData(
            Urls.Center.WITHDRAW_RECORDS,
            params,
            resultClass = WithdrawRecordsData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if(1==p)items.clear()
                it.list?.forEach {
                    items += WithdrawRecordItemModel(this@WithdrawRecordModel, ObservableField(it))
                }
            },
            finish = { stopRefreshOrLoadSingleLiveEvent.call() })
    }

}